<!-- 领奖列表-->
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="static/js/jquery-3.4.1.min.js"></script>
    <script src="static/layui/layui.js"></script>
    <#--  <script src="../../${request.contextPath}/static/layui/layui_exts/excel.js"></script>  -->
    <link rel="stylesheet" href="static/layui/css/layui.css">
</head>
<style>
  #test10{
    width: 290px;
  }
  .layui-input-inline{
    width: auto !important;
    min-width: 190px !important;
  }
</style>
<body>

<div class="layui-form">
    <div class="layui-form-item">
        <div class="layui-inline">
            <div class="layui-input-inline">
                <input type="text" class="layui-input" id="test10" placeholder="请选择发送时间" readonly="readonly">
            </div>
            <div class="layui-input-inline">
                <button class="layui-btn" id="search">查询</button>
            </div>
            <#--  <div class="layui-input-inline">
                <button type="button" class="layui-btn layui-btn-danger" id="export"><i class="layui-icon">&#xe67d;</i>导出Excel文件</button>
            </div>  -->
        </div>
    </div>
</div>
<script type="text/html" id="state">
    {{d.isReceive = d.isReceive == 0 ? "卡券未发放" : (d.isReceive == 1 ? "卡券已发放" : (d.isReceive == 2 ? "短信未发送" : "短信已发送"))}}
</script>
<table class="layui-hide" id="dept-table" lay-filter="dept-table"></table>

<script>
    var returnData;
    <#--  window.onload=function(){
        $.ajax({
            url: '${request.contextPath}/findAwardList',
            success: function(res){
                returnData = res.data;
            }
        });
    }  -->

    layui.use(['table','laydate'], function(){
        var table = layui.table;
        var laydate = layui.laydate;
        table.render({
            elem: '#dept-table',
            url:'${request.contextPath}/findAward',
            toolbar: '#toolbar',
            parseData: function (res) {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.size,
                    data: res.data
                }
            }
            ,cols: [[
                {field:'createdTime', width:180, title: '创建时间'},
                {field:'mobile', width:150, title: '手机号'},
                {field:'busCount', width:150, title: '公交次数'},
                {field:'taskId', width:170, title: '任务ID'},
                {field:'taskName', width:170, title: '任务名称'},
                {field:'ticketId', width:120, title:'卡券ID'},
                {field:'name', width:170, title: '卡券名称'},
                {field:'orderId', width:200, title:'订单号' },
                {field:'sendTime', width:180, title:'短信发送时间'},
                {field:'id', width:80, title: 'ID'}
            ]]
            ,page: true
        });
         //日期时间范围
        var ins1 = laydate.render({
            elem: '#test10'
            ,type: 'datetime'
            ,range: true
            ,ready: function(){
              $(".layui-laydate-footer [lay-type='datetime'].laydate-btns-time").click();
              // 改变结束时间默认值
              $(".laydate-main-list-1 .layui-laydate-content li ol li:last-child").click();
              $(".layui-laydate-footer [lay-type='date'].laydate-btns-time").click();
            }
        });
        table.on('toolbar(dept-table)', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            switch(obj.event){
                case 'addDept':
                    layer.open({
                        btn: '新建',
                        title: '添加奖品',
                        content: $("#dept-insert").text(),
                        offset: 'c',
                        area: ["500px", "300px"],
                        yes: function () {
                            var name = $("#dept-name").val();
                            var awardCount = $("#dept-awardCount").val();
                            var ticketId = $("#dept-ticketId").val();
                            if (name.length <= 0  || awardCount.length <= 0) {
                                if (name.length <= 0) {
                                    layer.tips('奖品名称不能为空', '#dept-name',  {
                                        tipsMore: true
                                    });
                                }
                                if (awardCount.length <= 0) {
                                    layer.tips('奖品数量不能为空', '#dept-awardCount', {
                                        tipsMore: true
                                    });
                                }
                                if (ticketId.length <= 0) {
                                    layer.tips('卡券ID不能为空', '#dept-ticketId', {
                                        tipsMore: true
                                    });
                                }
                            } else {
                                // 调用新建API
                                var nowDate = new Date();
                                $.ajax({
                                    url: '${request.contextPath}/award',
                                    method: 'post',
                                    data: {
                                        name: name,
                                        awardCount: awardCount,
                                        ticketId: ticketId,
                                        createdTime: nowDate
                                    },
                                    success: function (res) {
                                        if (res.code == 200) {
                                            // 执行局部刷新, 获取之前的TABLE内容, 再进行填充
                                            var dataBak = [];
                                            var tableBak = table.cache.dept-table;
                                            for (var i = 0; i < tableBak.length; i++) {
                                                dataBak.push(tableBak[i]);      //将之前的数组备份
                                            }
                                            dataBak.push({
                                                name: $("#dept-name"),
                                                awardCount: $("#dept-awardCount"),
                                                ticketId: $("#dept-ticketId"),
                                                createdTime: nowDate
                                            });
                                            //console.log(dataBak);
                                            table.reload("dept-table",{
                                                data:dataBak   // 将新数据重新载入表格
                                            });
                                            layer.msg('新建奖品成功', {icon: 1});
                                        } else {
                                            layer.msg('新建奖品失败', {icon: 2});
                                        }
                                    }
                                });
                            }
                        }
                    });
            }
        });
        //监听工具条(右侧)
        table.on('tool(dept-table)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            if(layEvent === 'edit'){ //编辑
                // 发送更新请求
                $.ajax({
                    url: '${request.contextPath}/award',
                    method: 'put',
                    data: JSON.stringify({
                        id: data.id,
                        name: data.name,
                        awardCount: data.awardCount
                    }),
                    contentType: "application/json",

                    success: function (res) {
                        if (res.code == 200) {
                            layer.msg('更改奖品信息成功', {icon: 1});
                            obj.update({
                                name: data.name,
                                awardCount: data.awardCount
                            });
                        } else {
                            layer.msg('更改奖品信息失败', {icon: 2});
                        }
                    }
                });
            } else if (layEvent == 'del') {
                layer.confirm('删除奖品' + data.name + '?', {skin: 'layui-layer-molv',offset:'c', icon:'0'},function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url: '${request.contextPath}/award/' + data.id,
                        type: 'delete',
                        success: function (res) {
                            if (res.code == 200) {
                                layer.msg('删除奖品成功', {icon: 1, skin: 'layui-layer-molv', offset:'c'});
                            } else {
                                layer.msg('删除奖品失败', {icon: 2, skin: 'layui-layer-molv', offset:'c'});
                            }
                        }
                    })
                });
            }
        });
    });
    //按钮点击查询事件
    $("#search").click(function(){
        var table = layui.table;
        var type = $("#type").val();
        var time = $("#test10").val();
        var sendTime = '';
        var endTime = '';
        var dataList = {};
        if(time != ''){//根据时间和申诉状态查询
            sendTime = StringToDate(time.substring(0,19));
            endTime = StringToDate(time.substring(22,42));
            dataList = {
                sendTime : sendTime,
                endTime : endTime
                };
            table.reload("dept-table",{
                url: '${request.contextPath}/findAward',
                where: dataList,
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                done: function(res){
                    this.where={};
                }
            });
            $.ajax({
                url: '${request.contextPath}/findAwardList',
                data: dataList,
                success: function(res){
                    returnData = res.data;
                }
            });           
        }else{//查询所有数据
            table.reload('dept-table',{
                url: '${request.contextPath}/awardlist',
                page: {
                    curr: 1
                },
                done: function(res){
                    this.where={};
                }
            });
            $.ajax({
                url: '${request.contextPath}/findAwardList',
                success: function(res){
                    returnData = res.data;
                }
            });
        }                    
    });
    function StringToDate(s) {//字符串转日期
        var d = new Date(); 
        d.setYear(parseInt(s.substring(0,4),10)); 
        d.setMonth(parseInt(s.substring(5,7)-1,10)); 
        d.setDate(parseInt(s.substring(8,10),10)); 
        d.setHours(parseInt(s.substring(11,13),10)); 
        d.setMinutes(parseInt(s.substring(14,16),10)); 
        d.setSeconds(parseInt(s.substring(17,19),10));
        return d; 
    }
    //导出功能
    var flag = false;
    $("#export").click(function(){
        if(!flag){
            returnData = LAY_EXCEL.filterExportData(returnData,{
                id: 'id',
                isReceive:function(value, line, data) {
                    return value = value == 0 ? "卡券未发放" : (value == 1 ? "卡券已发放" : (value == 2 ? "短信未发送" : "短信已发送")) ;
                },
                awardName: 'awardName',
                ticketId: 'ticketId',
                receiveTime: 'receiveTime',
                phone: 'phone',
                busCount: 'busCount',
                ticketMsg: 'ticketMsg',
                msg: 'msg',
                msgContent: 'msgContent'
            });
            returnData.unshift({id: 'ID',receiveTime: '领奖时间',awardName: '奖励名称',ticketId: '卡券ID',phone: '领奖手机号',busCount: '公交次数',isReceive: '领奖状态',
                            ticketMsg:'卡券响应信息', msg: '短信响应信息',msgContent:'短信内容'});
            flag = !flag;
        }
        if(flag){
            LAY_EXCEL.exportExcel({
                sheet1: returnData
            }, '表格导出.xlsx', 'xlsx');
        }
    });
</script>
</body>
</html>